package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.blog;
import com.example.demo.entity.comment;
import com.example.demo.entity.users;
import com.example.demo.mapper.commentMapper;
import com.example.demo.mapper.usersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
public class commentController {
    @Autowired
    commentMapper commentMapper;
    @Autowired
    usersMapper usersMapper;

    //查询评价根据博客id
    @GetMapping("/selectcommentByblogid/{id}")
    public String selectcommentByblogid(@PathVariable("id") int id)     {
        List<comment>list=commentMapper.selectcommentByblogid(id);
        for (int i=0;i<list.size();i++){
            list.get(i).setUsers(usersMapper.selectuser(list.get(i).getMailbox()).getNickname());
        }
        return list.toString();
    }

    //添加评价
    @ResponseBody
    @RequestMapping(value = "/insertcomment", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public comment insertcomment(@RequestBody JSONObject jsonParam) throws IOException {
        //获取系统时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        comment c = new comment();
        c.setComment(jsonParam.getString("comment"));
        c.setMailbox(jsonParam.getString("mailbox"));
        c.setBlogid(jsonParam.getInteger("blogId"));
        c.setTime(dateFormat.format(date));
        commentMapper.insertcomment(c);
        return c;
    }
}
